<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="line-height: 36px;">拦截管理</span>
        <el-button style="float: right;" type="primary" @click="dialogOpen('add')">新增拦截</el-button>
      </div>
      <s-table :table="table" @http="tableWatch">
        <el-form-item slot="multiSelect" label="多选操作" prop="multiSelect" v-if="table.multiSelect">
          <el-row>
            <el-col :span="8">
              <el-button size="small" type="danger" @click="tableMultiDelete">多选删除</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-table-column
          fixed="right"
          slot="operation"
          align="center"
          label="可用操作"
          width="100">
          <template scope="s">
            <el-button type="info" icon="edit" size="mini" @click="dialogOpen('PUT', s.row)"></el-button>
            <el-button type="danger" icon="delete" size="mini" @click="tableDelete(s.row)"></el-button>
          </template>
        </el-table-column>
      </s-table>
    </el-card>
    <s-dialog :dialog="dialog" :close="dialogInit" :closeTip="false">
      <p slot="title">{{dialog.title}}</p>
      <s-form :form="formDialog" ref="formDialog">
        <el-row>
          <el-col  :lg="{span: 10, offset: 0}">
            <el-form-item prop="url" label="拦截路径">
              <el-input type="text"
                        v-model="formDialog.url"
                        placeholder="拦截路径"></el-input>
            </el-form-item>
          </el-col>
          <el-col  :lg="{span: 10, offset: 2}">
            <el-form-item prop="transfertype" label="请求方式">
              <el-select v-model="formDialog.transfertype"  placeholder="请选择">
                <el-option label="GET" value="GET"></el-option>
                <el-option label="POST" value="POST"></el-option>
                <el-option label="PUT" value="PUT"></el-option>
                <el-option label="DELETE" value="DELETE"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :lg="{span: 10, offset: 0}">
            <el-form-item prop="appId" label="所属应用">
              <el-select v-model="formDialog.appId">
                <el-option
                  v-for="item in dialog.app"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="{span: 10, offset: 2}">
            <el-form-item prop="functionId" label="功能名称">
              <el-cascader
                v-model="formDialog.functionId"
                :props="{value:'key'}"
                :options="dialog.options"
                change-on-select
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </s-form>
      <el-button slot="footer" @click="dialogSave">保存</el-button>
    </s-dialog>
  </div>
</template>

<script>
  import {AutoVue} from '~/plugins/Tools';
  function _form () {
    return {
      url: {
        value: '',
        rule: [
          'vNull',
        ],
        notes: '拦截名称',
      },
      transfertype: {
        value: 'GET',
        notes: '请求路径',
      },
      functionId: {
        value: [],
        notes: '功能名称',
      },
      appId: {
        value: '',
        notes: '所属应用',
      },
      id: {
        value: 0,
        notes: 'ID',
      },
    };
  }

  export default AutoVue({
    store: ['DICTIONARY_custom', 'USER'],
    data: {
      table: {
        column: [
          {
            label: '拦截路径',
            prop: 'url',
            minWidth: '0px',
            search: true,
          },
          {
            label: '请求方式',
            prop: 'transfertype',
            minWidth: '0px',
            search: true,
          },
          {
            label: '功能名称',
            prop: 'show_functionId',
            minWidth: '0px',
            search: true,
          },
          {
            label: '所属应用',
            prop: 'show_appId',
            minWidth: '0px',
            search: true,
          },
        ],
        url: '/urlfun/',
        key: 'id',
        tableColumn: 4,
      },
      formDialog: _form(),
      dialog: {
        title: '新增',
        row: {},
        options: [],
        app: [],
      },
    },
    methods: {
      tableDelete (row) {
        this.$confirm('您将删除拦截信息。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            try {
              await this.post('/urlfun/delete/', [row.id]);
              this.tableWatch('table');
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
      },
      tableMultiDelete () {
        this.$confirm('您将删除这些拦截。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            let step = [];
            for (let item of this.table.multipleSelection) {
              step.push(item.id);
            }
            try {
              await this.post('/urlfun/delete/', step);
              this.tableWatch('table');
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
      },
      dialogInit () {
        this.formDialog = {
          ...this.formDialog,
          ...this.ObjectClone(_form()),
        };
        this.resetFields('formDialog');
      },
      async dialogOpen (type, more) {
        if (type) {
          type = type.toUpperCase();
        } else return;
        switch (type) {
        case 'ADD':
          this.dialog.title = '新增';
          this.formDialog.appId = this.USER.app.id;
          break;
        case 'PUT':
          this.dialog.title = '修改';
          this.formDialog = {
            ...this.formDialog,
            ...this.ObjectClone(_form(), more),
          };
          let {ids} = await this.get('/urlfun/searchfunc/' + this.formDialog.id);
          this.formDialog.functionId = ids;
          this.dialog.row = more;
          break;
        }
        if (this.dialog.app.length === 0) {
          this.dialog.app = await this.get('/app/getAll');
        }
        if (this.formDialog.appId !== this.USER.app.id || this.dialog.options.length === 0) {
          this.get('/function/tree/' + this.formDialog.appId)
            .then(array => {
              function checkArrayChildren (array) {
                let step = [];
                array.forEach(item => {
                  if (item.children && item.children.length === 0) {
                    delete item.children;
                    step.push(item);
                  } else {
                    step.push({
                      ...item,
                      children: checkArrayChildren(item.children),
                    });
                  }
                });
                return step;
              }
              this.dialog.options = checkArrayChildren(array);
            });
        }
        this.dialog.visible = true;
      },
      dialogSave () {
        if (this.dialog.title === '新增') {
          this.VALIDATE('formDialog', async option => {
            try {
              option.functionId = option.functionId[option.functionId.length - 1];
              let {id} = await this.post('/urlfun/add', option);
              this.table.data = [...await this.get('/urlfun/' + id), ...this.table.data];
              this.table.total++;
              this.resetFields('formDialog');
              this.dialog.visible = false;
            } catch (err) {
              console.log(err);
            }
          });
        } else {
          this.VALIDATE('formDialog', async option => {
            try {
              option.functionId = option.functionId[option.functionId.length - 1];
              await this.post('/urlfun/add', option);
              this.dialog.row = (await this.get('/urlfun/' + option.id))[0];
              this.resetFields('formDialog');
              this.dialog.visible = false;
            } catch (err) {
              console.log(err);
            }
          });
        }
      },
    },
    watch: {
      'formDialog.appId': async function () {
        if (this.formDialog.appId && this.formDialog.appId !== this.USER.app.id) {
          this.dialog.options = await this.get('/function/tree/' + this.formDialog.appId);
        }
      },
    },
    mounted: function () {
      this.tableWatch('table');
    },
  });
</script>

<style scoped lang="scss">
  .box-card {
    margin: 20px;
  }

  .createTimeSpan {
    display: block;
    margin-top: 34px;
  }

  @media screen and (max-width: 800px) {
    .createTimeSpan {
      margin-top: 0;
    }
    .box-card {
      margin: 0;
    }
  }

  .el-select {
    width: 100%;
  }
</style>
